//
//  STRegisterSetupPwdView.swift
//  iPhone
//
//  Created by Toj on 4/24/23.
//

import UIKit

protocol STRegisterSetupPwdViewDelegate: NSObjectProtocol {
    func registerSetupPwdViewDidTapClose(_ setupView: STRegisterSetupPwdView)
    func registerSetupPwdViewDidTapNext(_ setupView: STRegisterSetupPwdView, password: String)
}

class STRegisterSetupPwdView: UIView {
    
    weak var delegate: STRegisterSetupPwdViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
        setupMakeInitialize()
        setupMakeNotification()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* 背景View */
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.tt_alpha(0.5)
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapBackground))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 展示内容 */
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.cm_corner(radius: 24, corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapEndEditing))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 返回按钮 */
    private lazy var backButton: UIButton = {
        let view = UIButton()
        view.setImage("com_signin_back_icon".img_resource, for: .normal)
        view.addTarget(self, action: #selector(didTapClosed), for: .touchUpInside)
        return view
    }()
    
    /* 标题 */
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#333333".to_color
        view.font = 20.to_boldFont
        view.textAlignment = .center
        view.numberOfLines = 0
        view.text = "NewSignIn_Password".localized()
        return view
    }()
    
    /* 密码图标 */
    private lazy var passwordIcon: UIImageView = {
        let view = UIImageView()
        view.image = "com_password_lock_gray".img_resource
        return view
    }()
    
    /* 查看密码 */
    private lazy var displayButton: UIButton = {
        let view = UIButton()
        view.setImage("com_pwd_see_lock".img_resource, for: UIControl.State.normal)
        view.setImage("com_pwd_see_unlock".img_resource, for: UIControl.State.selected)
        view.addTarget(self, action: #selector(didTapDisplay(sender:)), for: .touchUpInside)
        view.frame.size = CGSize(width: 24, height: 24)
        return view
    }()
    
    private lazy var passwordTextField: FMTextField = {
        let view = FMTextField()
        
        view.textField.delegate = self
        view.textField.keyboardType = .asciiCapable
        view.textField.clearButtonMode = .whileEditing // 清空按钮
        view.textField.font = UIFont.systemFont(ofSize: 18)
        view.textField.textColor = .black
        let attributedPlaceholder = "register_input_create_password".localized().to_attributedString(font:  UIFont.systemFont(ofSize: 14), color: "#DDDDDD".to_color)
        view.textField.attributedPlaceholder = attributedPlaceholder
        
        view.lineNormalColor = "#999999".to_color
        
        view.rightView = displayButton
        return view
    }()
    
    
    /* 确认密码图标 */
    private lazy var confirmPasswordIcon: UIImageView = {
        let view = UIImageView()
        view.image = "com_password_lock_gray".img_resource
        return view
    }()
    
    /* 查看确认密码 */
    private lazy var displayConfirmButton: UIButton = {
        let view = UIButton()
        view.setImage("com_pwd_see_lock".img_resource, for: UIControl.State.normal)
        view.setImage("com_pwd_see_unlock".img_resource, for: UIControl.State.selected)
        view.addTarget(self, action: #selector(didTapDisplayConfirm(sender:)), for: .touchUpInside)
        view.frame.size = CGSize(width: 24, height: 24)
        return view
    }()
   
    /* 确认密码 */
    private lazy var confirmPasswordTextField: FMTextField = {
        let view = FMTextField()
        
        view.textField.delegate = self
        view.textField.keyboardType = .asciiCapable
        view.textField.clearButtonMode = .whileEditing // 清空按钮
        view.textField.font = UIFont.systemFont(ofSize: 18)
        view.textField.textColor = "#333333".to_color
        let placeholder = "confirm_new_pass".localized()
        let attributedPlaceholder = placeholder.to_attributedString(font:  UIFont.systemFont(ofSize: 14), color: "#DDDDDD".to_color)
        view.textField.attributedPlaceholder = attributedPlaceholder

        view.lineNormalColor = "#999999".to_color
        
        view.rightView = displayConfirmButton
        return view
    }()
 
    /* NEXT按钮 */
    private lazy var nextButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = "#0087EB".to_color
        view.titleLabel?.font = 14.to_boldFont
        view.setTitleColor(.white, for: .normal)
        view.setTitle("NEXT".localized(), for: .normal)
        let width = CGFloat.sr_width - 80
        view.frame = CGRect(origin: .zero, size: CGSize(width: width, height: 32.ui_scale))
        view.addTarget(self, action: #selector(didTapNext), for: .touchUpInside)
        view.cm_cornerRadius = 16.ui_scale
        return view
    }()
}

// MARK: - 点击事件
@objc private extension STRegisterSetupPwdView {
    
    func didTapBackground() {
        didTapClosed()
    }
    
    func didTapClosed() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        delegate?.registerSetupPwdViewDidTapClose(self)
    }
    
    func didTapNext() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        delegate?.registerSetupPwdViewDidTapNext(self, password: passwordTextField.stringValue)
    }
    
    func didTapDisplay(sender: UIButton) {
        print("-->toj: func:" + #function)
        sender.isSelected = !sender.isSelected
        passwordTextField.textField.isSecureTextEntry = sender.isSelected
    }
    
    func didTapDisplayConfirm(sender: UIButton) {
        print("-->toj: func:" + #function)
        sender.isSelected = !sender.isSelected
        confirmPasswordTextField.textField.isSecureTextEntry = sender.isSelected
    }
    
    func didTapEndEditing() {
        endEditing(true)
    }
    
    func keyboardWillShow(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let frameValue = info[UIResponder.keyboardFrameEndUserInfoKey]
        // 得到键盘frame
        let keyboardFrame = (frameValue as AnyObject).cgRectValue
        let kbHeight = keyboardFrame?.size.height ?? 303
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView(kbHeight)
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
    
    func keyboardWillHide(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView()
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
}

// MARK: - Public
extension STRegisterSetupPwdView {
    
    func show() {
        clearAccount()
        isHidden = false
        setNeedsLayout()
    }
    
    func hide() {
        isHidden = true
        removeFromSuperview()
    }
}

// MARK: - Private
private extension STRegisterSetupPwdView {
    
    func clearAccount() {
        passwordTextField.stringValue = ""
        confirmPasswordTextField.stringValue = ""
    }
}

extension STRegisterSetupPwdView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        didTapNext()
        return true
    }
}

// MARK: - 初始化设置
private extension STRegisterSetupPwdView {
    
    func setupMakeAddSubviews() {
        
        addSubview(backgroundView)
        
        addSubview(contentView)
        
        // 标题
        contentView.addSubview(titleLabel)
        // 关闭按钮
        contentView.addSubview(backButton)
        
        // 密码图标
        contentView.addSubview(passwordIcon)
        // 输入密码
        contentView.addSubview(passwordTextField)
        
        // 确认密码图标
        contentView.addSubview(confirmPasswordIcon)
        // 确认密码
        contentView.addSubview(confirmPasswordTextField)
         
        // NEXT
        contentView.addSubview(nextButton)
    }
    
    func setupMakeLayoutContentView(_ margin: CGFloat = 0) {
        print("-->toj: margin:\(margin)")
        contentView.snp.remakeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(356.ui_mscale)
            make.bottom.equalTo(-margin)
        }
    }
    
    func setupMakeLayoutSubviews() {
        
        backgroundView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        setupMakeLayoutContentView()
        backButton.snp.makeConstraints { make in
            make.left.top.equalTo(contentView)
            make.width.equalTo(48)
            make.height.equalTo(48)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView).inset(20)
            make.top.equalTo(contentView)
            make.height.equalTo(100.ui_mscale)
        }
        
        // 密码
        passwordTextField.snp.makeConstraints { make in
            make.left.equalTo(56)
            make.right.equalTo(contentView).inset(24)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.height.equalTo(33)
        }
        
        // 密码图标
        passwordIcon.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalTo(passwordTextField)
            make.right.equalTo(passwordTextField.snp.left).offset(-12)
        }
        
        // 确认密码
        confirmPasswordTextField.snp.makeConstraints { make in
            make.left.right.height.equalTo(passwordTextField)
            make.top.equalTo(passwordTextField.snp.bottom).offset(25)
        }
        
        // 确认密码图标
        confirmPasswordIcon.snp.makeConstraints { make in
            make.right.width.height.equalTo(passwordIcon)
            make.centerY.equalTo(confirmPasswordTextField)
        }
        
        // NEXT
        let size = nextButton.frame.size
        nextButton.snp.remakeConstraints { make in
            make.centerX.equalTo(contentView)
            make.top.equalTo(confirmPasswordTextField.snp.bottom).offset(40.ui_mscale)
            make.width.equalTo(size.width)
            make.height.equalTo(size.height)
        }
    }
    
    func setupMakeInitialize() {
        didTapDisplay(sender: displayButton)
        didTapDisplayConfirm(sender: displayConfirmButton)
    }
    
    func setupMakeNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
}
